<?php
namespace models;

class DbMysql{
	
	/**
	 * 数据库链接
	 */
	private $mysqliconn;
	
	/**
	 * 初始化链接数据库
	 */
	public function __construct(){
		$dbconfig = include 'conf/database.php';
		$mysqli = new \mysqli();
		if(!$this->mysqliconn){
			$mysqli->connect($dbconfig['hostname'], $dbconfig['user'], $dbconfig['pwd'], $dbconfig['dbname']);
		}
		if(mysqli_connect_error()){
			throw new \Exception('connect: '.$mysqli->error);
			exit;
		}else{
			$this->mysqliconn = $mysqli;
			mysqli_set_charset($this->mysqliconn,$dbconfig['charset']);
		}
	}
	
	/**
	 * 查询全部数据
	 */
	public function select($sql){
		$return = false;
		if($sql){
			$result = $this->mysqliconn->query($sql);
			if($result){
				$data = [];
				while($row = mysqli_fetch_assoc($result)){
					$data[] = $row;
				}
				$return = $data;
			}else{
				throw new \Exception('select: '.$this->mysqliconn->error);
			}
			$this->mysqliconn->close();
		}else{
			throw new \Exception('sql有误!');
			exit;
		}
		return $return;
	}
	
	/**
	 * 查询一条数据
	 */
	public function find($sql){
		$return = false;
		if($sql){
			$result = $this->mysqliconn->query($sql);
			if($result){
				$data = [];
				while($row = mysqli_fetch_assoc($result)){
					$data = $row;
				}
				$return = $data;
			}else{
				throw new \Exception('find: '.$this->mysqliconn->error);
			}
			$this->mysqliconn->close();
		}else{
			throw new \Exception('sql有误!');
			exit;
		}
		return $return;
	}
	
	/**
	 * 修改一条数据，返回true或false
	 */
	public function update($sql){
		$return = false;
		if($sql){
			if($this->mysqliconn->query($sql)){
				$return = true;
			}else{
				throw new \Exception('update: '.$this->mysqliconn->error);
			}
			$this->mysqliconn->close();
		}
		return $return;
	}
	
	/**
	 * 插入一条数据,成功后返回主键自增id
	 */
	public function insert($sql){
		$return = false;
		if($sql){
			if($this->mysqliconn->query($sql)){
				$return = mysqli_insert_id($this->mysqliconn);
			}else{
				throw new \Exception('insert: '.$this->mysqliconn->error);
			}
			$this->mysqliconn->close();
		}
		return $return;
	}
	
	/**
	 * mysql execute操作，删除可以使用该方法
	 */
	public function execute($sql){
		$return = false;
		if($sql){
			if($this->mysqliconn->query($sql)){
				$return = true;
			}else{
				throw new \Exception('execute: '.$this->mysqliconn->error);
			}
			$this->mysqliconn->close();
		}
		return $return;
	}
	
	//开始事物,false是关闭自动回滚，true开启自动回滚
	public function startCommit($start = false){
		$this->mysqliconn->autocommit($start);
	}
	
	//事物回滚
	public function rollback(){
		$this->mysqliconn->rollback();
	}
}
